home *** CD-ROM | disk | FTP | other *** search
- Path: erich.triumf.ca!bennett
- From: bennett@erich.triumf.ca (P.Bennett)
- Newsgroups: comp.lang.c
- Subject: Re: Can anyone help a newbie out ?
- Date: 11 Apr 1996 22:54 PST
- Organization: TRIUMF: Tri-University Meson Facility
- Distribution: world
- Message-ID: <11APR199622540287@erich.triumf.ca>
- References: <4kkf3r$5b0@darwin.nbnet.nb.ca>
- NNTP-Posting-Host: ftp.triumf.ca
- News-Software: VAX/VMS VNEWS 1.50
-
- In article <4kkf3r$5b0@darwin.nbnet.nb.ca>, lewwid@brunswickmicro.nb.ca (Jeff) writes...
- >I started reading a book on C, and i am stuck on one exercise, and i
- >know it's really simple, but i can't do it :(
- >
- >Problem:Write a function that accepts two strings. Count the number
- >of characters in each string, and return the pointer to the longer
- >string.
- >
- >This is what my lamer brain had to say ...
- >
- >#include <stdio.h>
- >
- >char *ptr, *ptr1;
-
- This reserves space for two pointers-to-char, but does not initialize them to
- point anywhere in particular, not does it reserve any space to store chars.
- You probably should say:
- char ptr[80], ptr1[80];
- (or change '80' as needed to accomodate the longest expected string.)
-
- > puts("Please enter in the first string :");
- > gets(ptr);
-
- Two important points:
- NEVER use gets(), unless you have a Really Good Reason.
- There is NEVER a good reason to use gets().
- Use fgets() instead. (_Always!_)
- fgets(ptr, 80, stdin);
-
- > while (*x != NULL)
-
- NULL is the "null pointer constant" and is not a char. Use:
- while (*x != '\0')
- > total += 1
- ^ a semicolon is needed here
- (there is a strlen() function that will do this for you.)
- Also, you aren't stepping through the array.
- I would probably do:
- int i = 0
- while(x[i++] != '\0')
- total += 1;
-
- > if (total < total2)
- > return *y;
-
- This should be "return y", to return a pointer to one array, *y returns the
- first char.
-
-
- Peter Bennett VE7CEI | Vessels shall be deemed to be in sight
- Internet: bennett@triumf.ca | of one another only when one can be
- Packet: ve7cei@ve7kit.#vanc.bc.ca | observed visually from the other
- TRIUMF, Vancouver, B.C., Canada | ColRegs 3(k)
- GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
- or: ftp://ftp-i2.informatik.rwth-aachen.de/pub/arnd/GPS/peter/index.html
-
-
-
-
-
-